<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-03-12 14:56:46
 * @Description  : 文件详情组件
-->
<template>
  <div class="source-desc-container flex flex-col justify-between">
    <div class="header flex items-center relative h-[60px]">
      <div
        v-if="showCloseIcon"
        class="absolute right-0 top-0 cursor-pointer w-[30px] h-[30px] flex justify-center items-center hover:(bg-blue-100)"
        @click="handleToChangeShowDesc"
      >
        <SvgIcon icon="chacha"></SvgIcon>
      </div>

      <!-- <n-image
        class="absolute left-0 top-0 opacity-10"
        width="100%"
        height="60px"
        src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
      /> -->
      <div class="pic ml-2 mr-3">
        <svg-icon :icon="renderFileIcon" size="40px"></svg-icon>
      </div>
      <div class="info flex-col justify-center">
        <div class="name text-[#666]">
          <n-ellipsis style="max-width: 200px">
            {{ explorerStore.curSourceDesc?.label || '' }}
          </n-ellipsis>
        </div>
        <div
          class="flex text-[#aaa] items-center"
          v-if="
            explorerStore.curSourceDesc &&
            [navTypeList.SOURCE, navTypeList.LINK_SHARE_DESC].includes(
              explorerStore.curSourceDesc.myType
            )
          "
        >
          <div class="size">
            <!-- {{ convertFromBytes(explorerStore.curSourceDesc.file.size || '0') }} -->
            {{
              explorerStore.curSourceDesc.file
                ? convertFromBytes(explorerStore.curSourceDesc.file.size)
                : '0'
            }}
          </div>
          ，
          <div class="time">
            {{ formatTime(explorerStore.curSourceDesc.createTime) }}
          </div>
          <!-- ， -->
          <!-- <SvgIcon
            icon="shoucangjiashangpin-copy"
            class="cursor-pointer"
          ></SvgIcon> -->
        </div>
      </div>
    </div>
    <n-tabs
      v-if="
        explorerStore.curSourceDesc &&
        [navTypeList.SOURCE, navTypeList.LINK_SHARE_DESC].includes(
          explorerStore.curSourceDesc.myType
        )
      "
      type="line"
      animated
      :placement="tabPlacement"
      v-model:value="activeTab"
      class="flex-1"
    >
      <n-tab-pane name="attr" tab="attr">
        <template #tab>
          <div class="flex flex-col justify-center items-center w-full">
            <i class="iconfont icon-jinggao"></i>
            <span>属性</span>
          </div>
        </template>
        <n-scrollbar class="scroll-height">
          <DescPanel></DescPanel>
        </n-scrollbar>
      </n-tab-pane>
      <n-tab-pane name="permission" tab="permission" v-if="hasSourceAuth">
        <template #tab>
          <div class="flex flex-col justify-center items-center w-full">
            <i class="iconfont icon-yewuquanxian"></i>
            <span>权限</span>
          </div>
        </template>
        <n-scrollbar class="scroll-height">
          <div class="actions flex justify-between mb-2">
            <div class="flex items-center">
              <left-line></left-line>指定用户权限
            </div>
            <n-popselect
              trigger="click"
              :options="[]"
              class="w-[300px]"
              display-directive="show"
              placement="right"
            >
              <template #header>
                <user-select
                  :canSelectDep="true"
                  @change-value="handleUserChange"
                  :default-user-ids="targetList.map((item) => item.id)"
                ></user-select>
              </template>
              <template #empty> <div></div> </template>
              <n-button class="flex items-center mt-1" size="small">
                <i class="iconfont icon-tianjiatianjiayonghu11 mr-1"></i>
                添加用户或部门
              </n-button>
            </n-popselect>
          </div>
          <AuthTable
            :target-list="targetList"
            :size-max-column="false"
            @change-target-list="handleChangeTargetList"
            @change-default-role-id="handleChangeDefaultRoleId"
          ></AuthTable>
          <div class="footer flex justify-end items-center mt-2">
            <!-- <n-button type="tertiary" @click="handleToCancelShare"
              >取消分享</n-button
            > -->
            <n-button
              class="mx-2 px-4 grent-btn"
              type="primary"
              size="small"
              @click="handleToUpdateDocAuth"
            >
              保存
            </n-button>
          </div>
        </n-scrollbar>
      </n-tab-pane>
      <!-- <n-tab-pane name="version" tab="version">
        <template #tab>
          <div class="flex flex-col justify-center items-center w-full">
            <i class="iconfont icon-008duihuakuang-3 text-[18px]"></i>
            <span>版本</span>
          </div>
        </template>
        <n-scrollbar class="scroll-height">
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
          <div>111</div>
        </n-scrollbar>
      </n-tab-pane> -->
      <n-tab-pane name="dynamic" tab="dynamic">
        <template #tab>
          <div class="flex flex-col justify-center items-center w-full">
            <i class="iconfont icon-xiaoxi"></i>
            <span>动态</span>
          </div>
        </template>

        <n-scrollbar class="scroll-height">
          <div
            class="h-[32px] flex items-center border-b-gray-200 border-b-width-[1px]"
          >
            <SvgIcon icon="tongzhi" color="#40a9ff" class="ml-2"></SvgIcon>
            文档动态
          </div>
          <SourceTimeLine
            :sourceId="explorerStore.curSourceDesc.key"
          ></SourceTimeLine>
        </n-scrollbar>
      </n-tab-pane>
    </n-tabs>
  </div>
</template>

<script setup lang="ts">
import { useMessage } from 'naive-ui'
import useExplorerStore from '@/stores/modules/explorer'
import type { IndexObj } from '@/types/commom'
import { navTypeList } from '@/constants/explorer'
import { convertFromBytes, formatTime } from '@/utils'
import { getFileTypeInfoByType } from '@/utils/commonBusiness'
import DescPanel from './DescPanel.vue'
import SourceTimeLine from './SourceTimeLine.vue'
import { authSource } from '@/api/source'
import { load } from '@/utils/loading'
import { PERMISSIONS } from '@/constants/permission'

const activeTab = ref('attr')
const message = useMessage()

const explorerStore = useExplorerStore()

const handleToChangeShowDesc = () => {
  explorerStore.setShowSourceDesc(
    '' + explorerStore.showDesc === '1' ? '0.75' : '1'
  )
}

const hasSourceAuth = computed(() => {
  return (
    explorerStore.curSourceDesc &&
    +explorerStore.curSourceDesc.targetType === 2 &&
    explorerStore.curSourceDesc.sourceRole &&
    (explorerStore.curSourceDesc.sourceRole.id === '1' ||
      (explorerStore.curSourceDesc.sourceRole.Permissions &&
        explorerStore.curSourceDesc.sourceRole.Permissions.some(
          (item: any) => item.ename === PERMISSIONS.DOC_MANAGE
        )))
  )
})

withDefaults(
  defineProps<{
    tabPlacement?: 'top' | 'bottom'
    showCloseIcon?: boolean
  }>(),
  {
    tabPlacement: 'bottom',
    showCloseIcon: true
  }
)

const renderFileIcon = computed(() => {
  if (explorerStore.curSourceDesc === undefined) {
    return 'home'
  }

  if (explorerStore.curSourceDesc!.myIcon) {
    return explorerStore.curSourceDesc!.myIcon
  } else {
    if (explorerStore.curSourceDesc!.label === '个人空间') {
      return 'home'
    }
    return getFileTypeInfoByType(explorerStore.curSourceDesc!.type).myIcon
  }
})

// ============================== 权限设置 ===================================
onMounted(() => {
  if (
    explorerStore.curSourceDesc &&
    explorerStore.curSourceDesc.SourceAuths &&
    explorerStore.curSourceDesc.SourceAuths.length
  ) {
    targetList.value = explorerStore.curSourceDesc!.SourceAuths.map(
      (item: any) => {
        return {
          targetType: +item.targetType,
          targetId: item.targetId,
          id: item.targetId,
          authRole: item.roleId,
          targetName:
            +item.targetType === 1 ? item.User.username : item.Department.name,
          avator: +item.targetType === 1 ? item.User.avator : ''
        }
      }
    )
  }
})
watch(
  () => explorerStore.curSourceDesc,
  (newValue) => {
    let sourceAuths = newValue ? newValue.sourceAuths : []
    // console.log('111', newValue)
    if (sourceAuths && sourceAuths.length) {
      targetList.value = sourceAuths.map((item: any) => {
        return {
          targetType: +item.targetType,
          targetId: item.targetId,
          id: item.targetId,
          authRole: item.roleId,
          targetName:
            +item.targetType === 1 ? item.User.username : item.Department.name,
          avator: +item.targetType === 1 ? item.User.avator : ''
        }
      })
    } else {
      targetList.value = []
    }
  },
  {
    deep: true
  }
)
const targetList = ref<IndexObj[]>([])
const authTableDefaultRoleId = ref('4')

const handleChangeTargetList = (list: IndexObj[]) => {
  targetList.value = list
}

// 用户或者部门选择发生了改变
const handleUserChange = (value: string | string[], depsInfo: IndexObj[]) => {
  // 选择的对象发生了改变，[a,b,c]---->[a,b,f,g,h]
  // 权限信息同步修改，a，b的暂时不需要变更（authRolen）

  // targetList保留 value还在的，其他删除
  // target原先没有的，进行添加

  console.log(depsInfo, 'depsInfo')

  targetList.value = targetList.value.filter((item) => {
    return value.includes(item.id)
  })

  // target现在没有的
  let moreTargets = depsInfo
    .filter((item) => {
      return !targetList.value.some((item2) => {
        return item2.id === item.id
      })
    })
    .map((item3) => {
      return {
        authRole: authTableDefaultRoleId.value,
        ...item3,
        targetName: item3.name || item3.username,
        pTargetName: item3.parent ? item3.parent.name : '',
        targetType: item3.username ? '1' : '2'
      }
    })

  targetList.value = targetList.value.concat(moreTargets)
}

const handleChangeDefaultRoleId = (value: string) => {
  authTableDefaultRoleId.value = value
}

const handleToUpdateDocAuth = () => {
  // console.log(targetList.value, 'target')
  load.show()
  authSource({
    sourceId: explorerStore!.curSourceDesc!.id,
    authTo: targetList.value.map((item) => {
      return {
        roleId: item.authRole,
        targetType: item.targetType,
        targetId: item.id
      }
    })
  })
    .then(() => {
      message.success('操作成功')
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}
</script>

<style scoped lang="scss">
.source-desc-container {
  :deep(.n-tabs-tab-pad) {
    width: 0;
  }
  :deep(.n-tabs-wrapper) {
    width: 100%;
  }
  :deep(.n-tabs-wrapper .n-tabs-tab-wrapper) {
    flex: 1 !important;
  }

  :deep(.n-tabs-wrapper .n-tabs-tab-wrapper .n-tabs-tab) {
    width: 100%;
  }
  :deep(.n-tabs-wrapper .n-tabs-tab-wrapper .n-tabs-tab__label) {
    width: 100%;
  }

  :deep(.scroll-height) {
    max-height: calc(100vh - 215px);
    height: calc(100vh - 215px);
  }

  .header {
    background: #f6faff;
    background-image: linear-gradient(190deg, #e5f6ff, #fdfeff);
    border-bottom: 1px solid #eee;
  }
}
</style>
